package com.youlu.myapplication.scratch;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;

/**
 * @author Administrator
 */
public class GsonUtils {
    private static Gson mGson;

    public static String toJson(Object obj) {
        return obj == null ? "" : getGsonInstance().toJson(obj);
    }

    public static <T> T fromJson(String str, Type type) {
        return getGsonInstance().fromJson(str, type);
    }

    public static <T> T fromJson(String str, Class<T> cls) {
        return getGsonInstance().fromJson(str, cls);
    }

    /**
     * 获取Gson对象实例
     *
     * @return
     */
    private static synchronized Gson getGsonInstance() {
        Gson gson;
        synchronized (GsonUtils.class) {
            if (mGson == null) {

                mGson = new GsonBuilder().registerTypeAdapter(Double.class, (JsonSerializer<Double>) (d, type, jsonSerializationContext) -> {
                    if (d == ((double) d.longValue())) {
                        return new JsonPrimitive(d.longValue());
                    }
                    return new JsonPrimitive(d);
                }).create();
            }
            gson = mGson;
        }
        return gson;
    }
}